package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.pojo.*;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
public class QuanZiApiImpl implements QuanZiApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //发布动态
    @Override
    public boolean savePublish(Publish publish) {

        //校验publish对象
        if (publish.getUserId()==null){
            return false;
        }
        //其他逻辑

        try {
            //填充publish数据
            publish.setId(ObjectId.get());
            publish.setCreated(System.currentTimeMillis());//发布时间
            publish.setSeeType(1);//查看权限 默认为1， 功能暂不实现

            //1.保存动态信息
            this.mongoTemplate.save(publish);

            //2.写入到相册表
            //构建相册表信息
            Album album=new Album();
            album.setId(ObjectId.get());
            album.setPublishId(publish.getId());//动态id
            album.setCreated(System.currentTimeMillis());

            //将相册对象写入到mongo中  ，表名为发布者用户id
            String collectionName="quanzi_album_"+publish.getUserId();
            this.mongoTemplate.save(album,collectionName);

            //3.查询当前 用户的好友数据，将动态数据写入到好友的时间线表中
            Query query = Query.query(Criteria.where("userId").is(publish.getUserId()));
            List<Users> users = this.mongoTemplate.find(query, Users.class);
            for (Users user : users) {

                //构造时间线表数据
                TimeLine timeLine = new TimeLine();
                timeLine.setId(ObjectId.get());
                timeLine.setUserId(publish.getUserId());
                timeLine.setPublishId(publish.getId());
                timeLine.setDate(System.currentTimeMillis());

                //保存时间线表数据，表名为好友id，表中useId为发布者id
                this.mongoTemplate.save(timeLine,"quanzi_time_line_"+user.getFriendId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            //// TODO: 2021/2/23 出错事务回滚，Mongo非集群模式不支持，暂不进行实现
        }

        return true;
    }

    //查询好友动态
    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
//        PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
        Query query = new Query().with(pageRequest);


        String tableName="quanzi_time_line_";
        if (null==userId){
            tableName+="recommend";
        } else {
            tableName+=userId;
        }

        //查询本用户的时间线表
        List<TimeLine> timeLines = this.mongoTemplate.find(query, TimeLine.class, tableName);

        List<ObjectId> ids=new ArrayList<>();
        for (TimeLine timeLine : timeLines) {
            ids.add(timeLine.getPublishId());
        }

        //查询动态信息
        Query queryPublish= Query.query(Criteria.where("id").in(ids)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(queryPublish, Publish.class);

        //封装分页对象
         PageInfo<Publish> pageInfo=new PageInfo<>();
         pageInfo.setPageNum(page);
         pageInfo.setPageSize(pageSize);
         pageInfo.setTotal(0);
         pageInfo.setRecords(publishList);

        return pageInfo;
    }

    @Override
    public boolean saveLikeComment(Long userId, String publishId) {

        //判断是否已经点赞，如果已点赞就返回
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(1);
        Query query = Query.query(criteria);
        long count = this.mongoTemplate.count(query, Comment.class);
        if (count>0){
            return false;
        }

        return this.saveComment(userId,publishId,1,null);
    }

    @Override
    public boolean removeComment(Long userId, String publishId, Integer commentType) {

        Criteria criteria = Criteria.where("userId").is(userId)
                                      .and("publishId").is(new ObjectId(publishId))
                                      .and("commentType").is(commentType);
        Query query = Query.query(criteria);

        DeleteResult deleteResult = this.mongoTemplate.remove(query, Comment.class);
        return deleteResult.getDeletedCount()>0;
    }

    @Override
    public boolean saveLoveComment(Long userId, String publishId) {

        //判断是否已经喜欢，如果已喜欢就返回
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId())
                .and("commentType").is(3);
        Query query = Query.query(criteria);
        long count = this.mongoTemplate.count(query, Comment.class);
        if (count>0){
            return false;
        }

        return this.saveComment(userId,publishId,3,null);

    }

    @Override
    public boolean saveComment(Long userId, String publishId, Integer type, String content) {

        try {
            Comment comment = new Comment();
            comment.setContent(content);
            comment.setIsParent(true);
            comment.setCommentType(type);
            comment.setPublishId(new ObjectId(publishId));
            comment.setUserId(userId);
            comment.setId(ObjectId.get());
            comment.setCreated(System.currentTimeMillis());

            this.mongoTemplate.save(comment);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    @Override
    public Long queryCommentCount(String publishId, Integer type) {

        Criteria criteria = Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(type);
        Query query = Query.query(criteria);

        return this.mongoTemplate.count(query,Comment.class);
    }

    @Override
    public Publish queryPublishById(String publishId) {
        Publish publish = this.mongoTemplate.findById(new ObjectId(publishId), Publish.class);
        return publish;
    }

    @Override
    public PageInfo<Comment> queryCommentList(String publishId, Integer page, Integer pageSize) {


        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));

        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                                            .and("commentType").is(2))
                                            .with(pageRequest);

        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);

        PageInfo<Comment> commentPageInfo=new PageInfo<>();
        commentPageInfo.setTotal(0);
        commentPageInfo.setPageSize(pageSize);
        commentPageInfo.setPageNum(page);

        commentPageInfo.setRecords(commentList);

        return commentPageInfo;
    }
}
